#include <functional>
#include <queue>
#include <iostream>
#include <memory>
#include <pthread.h>
#include <signal.h>
#include <stdlib.h>
pthread_cond_t cond = PTHREAD_COND_INITIALIZER;
pthread_mutex_t mutex = PTHREAD_MUTEX_INITIALIZER;
struct task {
	task(int id) : id(id) {}
	int id;
};

std::queue<task> cache;
//int index = 0;
class pcmodel {
	public:
		pcmodel(){}
		static void producer(int);

		static void *consumer(void *arg);

	private:
		static int index;
};
int pcmodel::index = 0;

void pcmodel::producer(int arg) {
	pthread_mutex_lock(&mutex);
	//这里可以通过用户传入的参数指定生产多少task

	cache.emplace(index++);
	cache.emplace(index++);

	pthread_mutex_unlock(&mutex);
	pthread_cond_broadcast(&cond);		
}
using voidp = void *;

voidp pcmodel::consumer(voidp arg) {
	while (true) {
		pthread_mutex_lock(&mutex);
		while (cache.empty()) {
			//while防止虚假唤醒
			//阻塞在这
			pthread_cond_wait(&cond, &mutex);
		}	
		//可以自己设置每次消费数量
		task t = cache.front();
		cache.pop();
		std::cout << "处理task" << t.id << "完成" << std::endl;
		pthread_mutex_unlock(&mutex);
		sleep(1);
	}	
}
int main() 
{	
	auto prodF = pcmodel::producer;
	auto consF = pcmodel::consumer;
	//auto prodF = std::bind(pcmodel::producer, std::placeholders::_1);
	//auto consF = std::bind(pcmodel::consumer, std::placeholders::_1);
	signal(15, prodF);
	pthread_t p1,p2;
	pthread_create(&p1, NULL, consF, NULL);
	pthread_create(&p2, NULL, consF, NULL);

	pthread_join(p1, NULL);
	pthread_join(p2, NULL);
	return 0;

}

